package com.template.config.websocket;

import jakarta.annotation.Resource;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Lazy;
import org.springframework.messaging.simp.config.MessageBrokerRegistry;
import org.springframework.scheduling.TaskScheduler;
import org.springframework.web.socket.config.annotation.EnableWebSocketMessageBroker;
import org.springframework.web.socket.config.annotation.StompEndpointRegistry;
import org.springframework.web.socket.config.annotation.WebSocketMessageBrokerConfigurer;


/*
 * 开启使用STOMP协议来传输基于代理（message broker）的消息
 * 启用后控制器支持@MessgeMapping注解
 * TransportHandlingSockJsService 存放连接对象实例
 */
@EnableWebSocketMessageBroker
@Configuration
public class WebSocketConfig implements WebSocketMessageBrokerConfigurer {

    private static final long HEART_BEAT = 5000;

    @Resource
    @Lazy
    private TaskScheduler messageBrokerTaskScheduler;

    @Override
    public void registerStompEndpoints(StompEndpointRegistry registry) {

        registry.addEndpoint("/ws") // 设置监听节点
                .addInterceptors(new WebSocketAuthInterceptor()) // 设置用户认证拦截器
                .setHandshakeHandler(new UserHandshakeHandler()) // 设置用户信息处理器
                .setAllowedOriginPatterns("*") // 设置跨域
                .withSockJS(); // 使用SockJS协议
    }

    @Override
    public void configureMessageBroker(MessageBrokerRegistry registry) {
        // 设置客户端接收消息地址的前缀
        // 客户端接收消息需要携带此前缀，服务端也需要
        // 必须设定，否则 @SendTo 会响应两次
        registry.enableSimpleBroker("/topic")
                .setHeartbeatValue(new long[]{HEART_BEAT, HEART_BEAT})
                .setTaskScheduler(messageBrokerTaskScheduler);
        // 设置服务端接收消息地址的前缀
        // 客户端发送消息需要携带此前缀，服务端不用
//        registry.setApplicationDestinationPrefixes();
        // 设置客户端接收单播消息地址的前缀
        // 客户端接收消息需要携带此前缀，服务端不用
        // 不可设置为空，默认为 /user
//        registry.setUserDestinationPrefix("/");
    }

}
